#include "highscore.h"
#include <QDebug>
#include <QInputDialog>
#include <QSettings>
#include <QDialog>
#include <QTableView>
#include <QVBoxLayout>
#include <QPushButton>
#include <QStandardItemModel>
#include <QStandardItem>
#include <QHeaderView>
#include <QMapIterator>
#include <QScrollBar>

const int KVisibleHighScores = 5;

HighScore::HighScore()
{
    restoreHighScores(m_highScoreList);
    if (m_highScoreList.isEmpty())
    {
        initHighScores(m_highScoreList);
    }
}

HighScore::~HighScore()
{
    storeHighScores(m_highScoreList);
}

void HighScore::suggestNewHighScore(HighScoreItem& newItem)
{
    qDebug() << "addNewScore - score:" << newItem.m_score << "level:" << newItem.m_level;
    bool handled = false;

    QListIterator<HighScoreItem> i(m_highScoreList);
    while(!handled && i.hasNext())
    {
        const HighScoreItem& item = i.next();
        int index = m_highScoreList.indexOf(item);
        if (index > 5)
        {
            qDebug() << "Didn't reach high score limits' " << newItem.m_score;
            handled = true;
        }
        else if( newItem.m_score > item.m_score )
        {
            qDebug() << "Reached to high score limits' " << newItem.m_score;
            if(queryName(m_latestName))
            {
                newItem.m_name = m_latestName;
                m_highScoreList.insert(index, newItem);
                qDebug() << "added " << m_latestName << " to high score table, index = " << index;
            }
        handled = true;
        }
    }

    if (!handled && m_highScoreList.count() < 5 )
        {
        if(queryName(m_latestName))
        {
            newItem.m_name = m_latestName;
            m_highScoreList.append(newItem);
            qDebug() << "added " << m_latestName << " to high score table";
        }

    }
}

bool HighScore::queryName(QString name)
{
    bool accepted = false;
    m_latestName = QInputDialog::getText(this, tr("New high score"), tr("Enter your name:"), QLineEdit::Normal, m_latestName, &accepted);
    if (!accepted)
    {
        qDebug() << "User cancel high score query";
    }
    return accepted;
}

void HighScore::initHighScores(QList<HighScoreItem>& highScoreList)
{
    qDebug() << "Initializing highscore list...";
    HighScoreItem item1( QString("Mikki Hiiri"), 30, 3 );
    highScoreList.append(item1);
    HighScoreItem item2( QString("Aku Ankka"), 20, 2 );
    highScoreList.append(item2);
    HighScoreItem item3( QString("Hessu Hopo"), 10, 1 );
    highScoreList.append(item3);
}

void HighScore::restoreHighScores(QList<HighScoreItem>& highScoreList)
{
    qDebug() << "Restore highscores";
    QSettings settings("arithmetic_game");

    int count = settings.beginReadArray("highscorelist");

    for(int i=0; i<count; ++i)
    {
        settings.setArrayIndex(i);
        qDebug() << "restoring: " << settings.value("score").toInt() << ": " << settings.value("name").toString() << ":" << settings.value("level").toInt();
        HighScoreItem item(  settings.value("name").toString(), settings.value("score").toInt(), settings.value("level").toInt() );
        highScoreList.append(item);
    }
    settings.endArray();
}

void HighScore::storeHighScores(const QList<HighScoreItem>& highScoreList)
{
    qDebug() << "Store highscores";
    QSettings settings("arithmetic_game");

    QListIterator<HighScoreItem> i(highScoreList);
    settings.beginWriteArray("highscorelist");

    int index = 0;
    while(i.hasNext())
    {
        const HighScoreItem& item = i.next();
        qDebug() << "storing: " << item.m_name << ": " << item.m_score << item.m_level;
        settings.setArrayIndex(index);
        settings.setValue("score", item.m_score);
        settings.setValue("name", item.m_name);
        settings.setValue("level", item.m_level);
        index++;
    }
    settings.endArray();
}

void HighScore::resetHighScore()
{
    m_highScoreList.clear();
    initHighScores(m_highScoreList);
}

void HighScore::showHighscore()
{
    //Just wanted to do this by hands (always used designer before).
    qDebug() << "HighScore::showHighscore";
    QDialog* dialog = new QDialog(this);
    dialog->setWindowTitle( tr("High scores"));
    QTableView* table = new QTableView(dialog);
    QPushButton* button = new QPushButton(tr("OK"),dialog);

    connect( button, SIGNAL(pressed()), dialog, SLOT(close()));

    //populate model
    QStandardItemModel model;
    model.setHorizontalHeaderItem(0, new QStandardItem(tr("score")));
    model.setHorizontalHeaderItem(1, new QStandardItem(tr("name")));
    model.setHorizontalHeaderItem(2, new QStandardItem(tr("level")));

    QListIterator<HighScoreItem> i(m_highScoreList);
    int index = 0;

    while(i.hasNext() && index < KVisibleHighScores)
    {
        const HighScoreItem& item = i.next();
        model.setItem(index,0, new QStandardItem(QString::number(item.m_score)));
        model.setItem(index,1, new QStandardItem(item.m_name));
        model.setItem(index,2, new QStandardItem(QString::number(item.m_level)));
        index++;
    }

    table->setShowGrid(true);
    table->setCornerButtonEnabled(false);
    table->horizontalHeader()->setVisible(true);
    table->verticalHeader()->setVisible(false);
    table->setSelectionMode(QAbstractItemView::NoSelection);
    table->setModel(&model);

    QVBoxLayout* layout = new QVBoxLayout(dialog);
    layout->addWidget(table);
    layout->addWidget(button); //how about devices without touch support and no mouse?
    dialog->setLayout(layout);
    dialog->adjustSize();
    table->setBaseSize(table->sizeHint());
    layout->update();
    dialog->exec();
}

//end of file

